<template>
  <div class="order">
    <van-nav-bar
      title="我的订单"
      left-arrow
      @click-left="$router.push('/cart')"
      fixed
    />
    
    <div class="content" style="padding-top: 46px;">
      <!-- 订单状态切换 -->
      <van-tabs v-model="activeTab">
        <van-tab title="全部"/>
        <van-tab title="待付款"/>
        <van-tab title="待发货"/>
        <van-tab title="待收货"/>
        <van-tab title="已完成"/>
      </van-tabs>

      <!-- 订单列表 -->
      <div class="order-list">
        <van-card
          v-for="order in orderList"
          :key="order.id"
          :num="getOrderQuantity(order)"
          :price="order.total"
          :title="getOrderTitle(order)"
          :thumb="order.products[0].image"
        >
          <template #tags>
            <van-tag type="danger">{{ order.status }}</van-tag>
          </template>
          <template #footer>
            <van-button size="mini" v-if="order.status === '待付款'">
              去支付
            </van-button>
            <van-button size="mini" v-if="order.status === '待收货'">
              确认收货
            </van-button>
          </template>
        </van-card>
      </div>

      <!-- 加载状态 -->
      <van-empty v-if="orderList.length === 0" description="暂无订单"/>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="active" route>
      <van-tabbar-item icon="home-o" to="/">首页</van-tabbar-item>
      <van-tabbar-item icon="apps-o" to="/category">分类</van-tabbar-item>
      <van-tabbar-item icon="cart-o" :badge="cartCount" to="/cart">购物车</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/order">订单</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import { getOrders } from '@/api'
import { mapState } from 'vuex'

export default {
  name: 'Order',
  data() {
    return {
      active: 3, // 默认选中订单标签
      activeTab: 0,
      allOrders: [],
      statusList: ['全部', '待付款', '待发货', '待收货', '已完成']
    }
  },
  computed: {
    ...mapState({
      cartList: state => state.cartList
    }),
    cartCount() {
      return this.cartList.length || ''
    },
    orderList() {
      if (this.activeTab === 0) {
        return this.allOrders
      }
      const status = this.statusList[this.activeTab]
      return this.allOrders.filter(order => order.status === status)
    }
  },
  created() {
    this.fetchOrders()
  },
  methods: {
    async fetchOrders() {
      try {
        const res = await getOrders()
        if (res.code === 0) {
          this.allOrders = res.data
        }
      } catch (error) {
        console.error(error)
      }
    },
    getOrderQuantity(order) {
      return order.products.reduce((total, item) => total + item.quantity, 0)
    },
    getOrderTitle(order) {
      const titles = order.products.map(item => item.title)
      return titles.join('、')
    }
  }
}
</script>

<style scoped>
.order-list {
  padding: 10px;
}
.van-card {
  margin-bottom: 10px;
  background-color: #fff;
}
.content {
  min-height: calc(100vh - 146px);
}
</style> 